package com.mini.gateway.core.modules.route.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册中心服务缓存
 *
 */
@Component
public class InstanceCache implements ApplicationListener<RefreshRoutesEvent> {

    private static final Map<String, List<ServiceInstance>> cache = new HashMap<>();

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public void onApplicationEvent(RefreshRoutesEvent refreshRoutesEvent) {
        List<String> serviceIdList = discoveryClient.getServices();
        // 更新最新服务
        for (String serviceId : serviceIdList) {
            cache.put(serviceId, discoveryClient.getInstances(serviceId));
        }

        // 剔除已经失效的服务
        if (CollectionUtils.isNotEmpty(cache.keySet())) {
            for (String key : cache.keySet()) {
                if (!serviceIdList.contains(key)) {
                    cache.remove(key);
                }
            }
        }
    }

    public Map<String, List<ServiceInstance>> cache() {
        return cache;
    }
}
